<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import { RefreshLeft, Search } from "@element-plus/icons-vue";
import { ElForm } from "element-plus";
import { useRoute } from "vue-router";
import { getVppUserListAll } from "@/api/vppUser";
import moment from "moment";
import { getGainMounthUser, getGainMounthVpp } from "@/api/dayDetailedIncome";
import VChart from "@/views/monitor/server/components/VChart.vue";
import { dayRangeArray } from "@/utils";
const route = useRoute();
const activeUserId = ref(route.query?.id);
const activeName = ref("first");
const twoEchart = ref(null);
const allUser = reactive({
  data: []
});
const allVppUser = reactive({
  data: [
    {
      id: 1,
      name: "测试场站"
    }
  ]
});
const loading = ref(false);
const queryForm = reactive({
  data: {
    activeUserId: activeUserId.value,
    activeTime: []
  }
});
const queryFormTwo = reactive({
  data: {
    activeUserId: undefined,
    activeTime: []
  }
});
const optionsOne = ref({
  dataZoom: [
    {
      show: true,
      type: "inside",
      start: 0,
      end: 100
    },
    {
      show: true,
      type: "slider",
      start: 0,
      end: 100
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    show: true
  },
  xAxis: {
    type: "category",
    axisLabel: {
      //x轴文字的配置
      show: true
      // interval: 0,//使x轴文字显示全
    },
    // splitLine: {
    //   show: true,
    //   interval: (index, value) => {
    //     if (value.indexOf("00:00:00") > -1) {
    //       return true;
    //     } else {
    //       return false;
    //     }
    //   },
    //   lineStyle: {
    //     type: "solid",
    //     width: 1.3
    //   }
    // },
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: "value",
    show: true,
    min: "dataMin",
    axisLine: {
      show: true // 显示Y轴线
    }
  },
  series: [
    {
      name: "月内每日用户收益",
      type: "line",
      showSymbol: false,
      smooth: true,
      data: []
    }
  ]
});
const optionsTwo = ref({
  dataZoom: [
    {
      show: true,
      type: "inside",
      start: 0,
      end: 100
    },
    {
      show: true,
      type: "slider",
      start: 0,
      end: 100
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    show: true
  },
  xAxis: {
    type: "category",
    axisLabel: {
      //x轴文字的配置
      show: true
      // interval: 0,//使x轴文字显示全
    },
    // splitLine: {
    //   show: true,
    //   interval: (index, value) => {
    //     if (value.indexOf("00:00:00") > -1) {
    //       return true;
    //     } else {
    //       return false;
    //     }
    //   },
    //   lineStyle: {
    //     type: "solid",
    //     width: 1.3
    //   }
    // },
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: "value",
    show: true,
    min: "dataMin",
    axisLine: {
      show: true // 显示Y轴线
    }
  },
  series: [
    {
      name: "月内每日虚拟电厂收益",
      type: "line",
      showSymbol: false,
      smooth: true,
      data: []
    }
  ]
});
const showData = reactive({
  data: []
});
const showDataTwo = reactive({
  data: []
});
const timeChange = e => {};
const dataFormat = data => {
  let totalData = {};
  data
    .filter(item => item.dataType === 1)
    .forEach(item => {
      let year = item.dataMonth.split(" ")[0].split("-")[0];
      let month = item.dataMonth.split(" ")[0].split("-")[1];
      let len = moment(year + "-" + month).daysInMonth();
      for (let i = 1; i <= len; i++) {
        totalData[`${year}-${month}-${i > 9 ? i : "0" + i}`] =
          item[`p${i > 9 ? i : "0" + i}`];
      }
    });
  let days = [];
  if (queryForm.data.activeTime && queryForm.data.activeTime.length) {
    days = dayRangeArray(
      queryForm.data.activeTime[0] + "-01",
      queryForm.data.activeTime[1] === moment().format("YYYY-MM")
        ? moment().format("YYYY-MM-DD")
        : queryForm.data.activeTime[1] +
            "-" +
            moment(queryForm.data.activeTime[1]).daysInMonth()
    );
  } else {
    days = [];
  }
  let allData = [];
  days.forEach(i => {
    let item = {};
    item.dataMonth = i + " 00:00:00";
    allData.push(item);
  });
  // for (let i = 0; i < allData.length; i++) {
  //   for (let j = 0; j < data.length; j++) {
  //     if (
  //       allData[i].dataMonth === data[j].dataMonth &&
  //       data[j].dataType === 1
  //     ) {
  //       allData[i] = Object.assign({}, allData[i], data[j]);
  //     }
  //   }
  // }
  let start = (1 - 1 / allData.length) * 100;
  allData.forEach(item => {
    item.dataMonth = item.dataMonth.split(" ")[0];
    item.value = totalData[item.dataMonth.split(" ")[0]];
  });
  optionsOne.value.xAxis.data = allData.map(i => i.dataMonth);
  optionsOne.value.dataZoom[0].start = start;
  optionsOne.value.dataZoom[1].start = start;
  optionsOne.value.series[0].data = allData.map(i => i.value || null);
  showData.data = allData.map(item => {
    return {
      label: item.dataMonth,
      value: item.value || null
    };
  });
};
const dataFormatTwo = data => {
  let totalData = {};
  data
    .filter(item => item.dataType === 1)
    .forEach(item => {
      let year = item.dataMonth.split(" ")[0].split("-")[0];
      let month = item.dataMonth.split(" ")[0].split("-")[1];
      let len = moment(year + "-" + month).daysInMonth();
      for (let i = 1; i <= len; i++) {
        totalData[`${year}-${month}-${i > 9 ? i : "0" + i}`] =
          item[`p${i > 9 ? i : "0" + i}`];
      }
    });
  let days = [];
  if (queryFormTwo.data.activeTime && queryFormTwo.data.activeTime.length) {
    days = dayRangeArray(
      queryFormTwo.data.activeTime[0] + "-01",
      queryFormTwo.data.activeTime[1] === moment().format("YYYY-MM")
        ? moment().format("YYYY-MM-DD")
        : queryFormTwo.data.activeTime[1] +
            "-" +
            moment(queryFormTwo.data.activeTime[1]).daysInMonth()
    );
  } else {
    days = [];
  }
  let allData = [];
  days.forEach(i => {
    let item = {};
    item.dataMonth = i + " 00:00:00";
    allData.push(item);
  });

  // for (let i = 0; i < allData.length; i++) {
  //   for (let j = 0; j < data.length; j++) {
  //     if (
  //       allData[i].dataMonth === data[j].dataMonth &&
  //       data[j].dataType === 1
  //     ) {
  //       allData[i] = Object.assign({}, allData[i], data[j]);
  //     }
  //   }
  // }
  allData.forEach(item => {
    item.dataMonth = item.dataMonth.split(" ")[0];
    item.value = totalData[item.dataMonth.split(" ")[0]];
  });
  let start = (1 - 1 / allData.length) * 100;
  optionsTwo.value.xAxis.data = allData.map(i => i.dataMonth);
  optionsTwo.value.dataZoom[0].start = start;
  optionsTwo.value.dataZoom[1].start = start;
  optionsTwo.value.series[0].data = allData.map(i => i.value || null);

  showDataTwo.data = allData.map(item => {
    return {
      label: item.dataMonth,
      value: item.value || null
    };
  });
};
const init = async () => {
  let res = await getVppUserListAll();
  allUser.data = res.map(i => ({ ...i, id: i.id + "" }));
  queryForm.data.activeTime = [
    moment().subtract("month", 3).format("YYYY-MM"),
    moment().format("YYYY-MM")
  ];
  queryFormTwo.data.activeTime = [
    moment().subtract("month", 3).format("YYYY-MM"),
    moment().format("YYYY-MM")
  ];
  if (queryForm.data.activeUserId) {
    loading.value = true;
    let data = await getGainMounthUser({
      vppUserId: queryForm.data.activeUserId,
      begin: queryForm.data.activeTime[0] + "-01",
      end:
        queryForm.data.activeTime[1] === moment().format("YYYY-MM")
          ? moment().format("YYYY-MM-DD")
          : queryForm.data.activeTime[1]
    });
    dataFormat(data);
    loading.value = false;
  } else {
    dataFormat([]);
  }
};
const disabledTime = e => {
  return e.getTime() > new Date().getTime();
};
const search = async () => {
  if (
    queryForm.data.activeUserId &&
    queryForm.data.activeTime &&
    queryForm.data.activeTime.length
  ) {
    loading.value = true;
    let data = await getGainMounthUser({
      vppUserId: queryForm.data.activeUserId,
      begin: queryForm.data.activeTime[0] + "-01",
      end:
        queryForm.data.activeTime[1] === moment().format("YYYY-MM")
          ? moment().format("YYYY-MM-DD")
          : queryForm.data.activeTime[1] +
            "-" +
            moment(queryForm.data.activeTime[1]).daysInMonth()
    });
    dataFormat(data);
    loading.value = false;
  } else {
    dataFormat([]);
  }
};
const SearchTwo = async () => {
  if (
    queryFormTwo.data.activeUserId &&
    queryFormTwo.data.activeTime &&
    queryFormTwo.data.activeTime.length
  ) {
    loading.value = true;
    let data = await getGainMounthVpp({
      vppId: queryFormTwo.data.activeUserId,
      begin: queryFormTwo.data.activeTime[0] + "-01",
      end:
        queryFormTwo.data.activeTime[1] === moment().format("YYYY-MM")
          ? moment().format("YYYY-MM-DD")
          : queryFormTwo.data.activeTime[1] +
            "-" +
            moment(queryFormTwo.data.activeTime[1]).daysInMonth()
    });
    dataFormatTwo(data);
    loading.value = false;
  } else {
    dataFormatTwo([]);
  }
};

const resetQuery = () => {
  queryForm.data = {
    activeUserId: route.query?.id,
    activeTime: [
      moment().subtract("month", 3).format("YYYY-MM"),
      moment().format("YYYY-MM")
    ]
  };
};

const resetQueryTwo = () => {
  queryFormTwo.data = {
    activeUserId: undefined,
    activeTime: [
      moment().subtract("month", 3).format("YYYY-MM"),
      moment().format("YYYY-MM")
    ]
  };
};
const cactiveName = ref("first");
const c2activeName = ref("first");
const columns = [
  {
    key: "label",
    dataKey: "label",
    title: "时间",
    width: "50%"
  },
  {
    key: "value",
    dataKey: "value",
    title: "用户收益",
    width: "50%"
  }
];
const columns2 = [
  {
    key: "label",
    dataKey: "label",
    title: "时间",
    width: "50%"
  },
  {
    key: "value",
    dataKey: "value",
    title: "虚拟电厂收益",
    width: "50%"
  }
];
onMounted(() => {
  init();
});
const chartsLoading = ref(false);
</script>

<template>
  <div class="main h-[calc(100%-29px)]">
    <el-card v-loading="loading" class="w-full my-card-full">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="月内每日用户收益" name="first" />
        <el-tab-pane label="月内每日虚拟电厂收益" name="second" />
      </el-tabs>
      <div
        v-if="activeName === 'first'"
        key="1"
        class="one flex-1 flex flex-col"
      >
        <el-form :inline="true" :model="queryForm.data" label-width="0px">
          <el-form-item>
            <el-select
              v-model="queryForm.data.activeUserId"
              placeholder="选择用户"
              style="width: 240px"
            >
              <el-option
                v-for="item in allUser.data"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="queryForm.data.activeTime"
              :disabled-date="disabledTime"
              unlink-panels
              type="monthrange"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="YYYY-MM"
              date-format="YYYY-MM"
              @change="timeChange"
            />
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="search"
              >查询</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-tabs v-model="cactiveName">
          <el-tab-pane label="图表" name="first" />
          <el-tab-pane label="列表" name="second" />
        </el-tabs>
        <div
          v-if="cactiveName === 'first'"
          v-loading="chartsLoading"
          style="width: 99%"
          class="flex-1"
        >
          <v-chart :options="optionsOne" />
        </div>
        <div
          v-if="cactiveName === 'second'"
          v-loading="chartsLoading"
          style="width: 99%"
          class="flex-1"
        >
          <el-table-v2
            :columns="columns"
            :data="showData.data"
            :width="1614"
            :height="600"
            :scrollbar-always-on="false"
          />
        </div>
      </div>
      <div
        v-if="activeName === 'second'"
        key="2"
        class="two flex-1 flex flex-col"
      >
        <el-form :inline="true" :model="queryFormTwo.data" label-width="0px">
          <el-form-item>
            <el-select
              v-model="queryFormTwo.data.activeUserId"
              placeholder="选择用户"
              style="width: 240px"
            >
              <el-option
                v-for="item in allVppUser.data"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="queryFormTwo.data.activeTime"
              :disabled-date="disabledTime"
              unlink-panels
              type="monthrange"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="YYYY-MM"
              date-format="YYYY-MM"
            />
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="SearchTwo"
              >查询</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQueryTwo"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-tabs v-model="c2activeName">
          <el-tab-pane label="图表" name="first" />
          <el-tab-pane label="列表" name="second" />
        </el-tabs>
        <div
          v-if="c2activeName === 'first'"
          v-loading="chartsLoading"
          style="width: 99%"
          class="flex-1"
        >
          <v-chart ref="twoEchart" :options="optionsTwo" />
        </div>
        <div
          v-if="c2activeName === 'second'"
          v-loading="chartsLoading"
          style="width: 99%"
          class="flex-1"
        >
          <el-table-v2
            :columns="columns2"
            :data="showDataTwo.data"
            :width="1614"
            :height="600"
            :scrollbar-always-on="false"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.my-card-full {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
  }
}
</style>
